<template>
    <div class="select">
      <div><div class="text-overflow">{{selected}}</div></div>
      <div>
        <svg width="12" height="8" viewBox="0 0 12 8" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M5.99999 4.97665L10.125 0.851654L11.3033 2.02999L5.99999 7.33332L0.696655 2.02999L1.87499 0.851654L5.99999 4.97665Z" fill="white"/>
        </svg>
      </div>
      <div class="select-dropdown">
        <div v-for="(item, index) in options" :key="index" @click="onItemClick(item)">
          {{item[$props.valueField || 'name']}}
        </div>
        <div v-if="!options.length" :style="{color: 'white', textAlign: 'center', padding: '24px'}">
          {{$props.empty || '没有相关数据'}}
        </div>
      </div>
    </div>
</template>
<script setup lang="ts">
// 一个简单的 select 控件，可以控制颜色，背景，等等
import { onMounted, ref } from 'vue';
const props = defineProps(['options', 'placeholder', 'dropdownClass', 'dropdownWidth', 'empty', 'valueField', 'value'])
const emit = defineEmits(['change'])
const selected = ref(!props.value ? props.placeholder : props.value)

const onItemClick = (item: any) => {
    selected.value = item[props.valueField || 'name']
    emit('change', item)
}

onMounted(() => {
  if(props.value) {
    var d = props.options.find((item: any) => item[props.valueField || 'name'] === props.value);
    if(d) {
      emit('change', d)
    }
  }
})
</script>
<style lang="scss" scoped>
.select {
    border: 1px solid rgba(138, 158, 174, 1);
    background: rgba(0, 0, 0, 0.15);
    width: 100%;
    height: 38px;

    display: flex;
    align-items: center;
    color: white;
    padding: 0 12px;
    font-size: 16px;

    position: relative;
    box-sizing: border-box;
    cursor: pointer;

    > div:first-child {
        flex: 1 1 0%;
        overflow: hidden;
    }

    &:hover {
        background: rgba(0, 0, 0, 0.4);

        .select-dropdown {
            display: block;
        }
    }

    .select-dropdown {
        position: absolute;
        top: calc(100% + 2px);
        left: 0;
        min-width: 100%;
        max-height: 260px;
        overflow: overlay;
        width: v-bind('props.dropdownWidth');
        display: none;
        background: rgba(0, 0, 0, 0.4);

        > div {
            padding: 6px 12px;
            cursor: pointer;
            font-size: 16px;

            &:hover {
                background: rgba(0, 0, 0, 0.2);
            }
        }
    }

    .text-overflow {
        // width: calc(100% - 50px);
        // width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 100%;
    }
}
</style>